package com.baymax.test.scene.demo

import android.graphics.SurfaceTexture
import android.media.MediaPlayer
import android.opengl.GLSurfaceView
import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.FrameLayout
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.baymax.test.scene.BaseScene
import com.baymax.test.scene.addButton
import com.baymax.test.scene.newScrollContainer
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import kotlin.coroutines.suspendCoroutine


/**
 * @title:       标题
 * @project:     TestScene
 * @package:     com.baymax.test.scene.demo
 * @class:       MediaPlayerScene
 * @description:
 * <p>
 * 类描述
 * </p>
 *
 * @version:   1.0
 * @createDate:   2022/8/8 13:54
 * @Copyright (C) 2022 YSTEN
 * @author:       xuyujian
 */
class MediaPlayerScene : BaseScene() {

    lateinit var m: MediaPlayer

    val empty = Result.failure<SurfaceHolder>(Throwable("null"))
    private val surfaceF = MutableStateFlow(empty)
    private lateinit var surfaceView: SurfaceView

    val s =
        "http://223.110.242.36/wh7f454c46tw492375642_-1418223143/ott.mobaibox.com/3/16/20210520/282557590/282557590.ts?OTTUserToken&servicetype=0&icpid=3&RTS=1673491549&from=36&hms_devid=2188&vqe=3"

    override fun onCreateView(p0: LayoutInflater, p1: ViewGroup, p2: Bundle?): View {
        return p1.newScrollContainer {
            val s1 = SurfaceView(requireSceneContext())
            surfaceView = s1
            surfaceView.holder.addCallback(object : SurfaceHolder.Callback {
                override fun surfaceCreated(holder: SurfaceHolder) {
                    Log.d(TAG, "surfaceCreated: ${holder.surface}")
                    surfaceF.tryEmit(Result.success(holder))
                }

                override fun surfaceChanged(
                    holder: SurfaceHolder,
                    format: Int,
                    width: Int,
                    height: Int
                ) {
                    Log.d(TAG, "surfaceChanged: ")
                }

                override fun surfaceDestroyed(holder: SurfaceHolder) {
                    Log.d(TAG, "surfaceDestroyed: ")
                    surfaceF.tryEmit(empty)
                }
            })

            addButton("switch texture") {
                launch {
                    release()
                    startComplex()
                }
            }
            val p = FrameLayout(requireSceneContext()).apply {
                addView(s1)
            }
            addView(p, ViewGroup.MarginLayoutParams(480, 480).apply {
                leftMargin = 120
                rightMargin = 120
            })

            addButton("gone") {
                s1.visibility = if (s1.visibility == View.GONE) View.VISIBLE else View.GONE
            }

            addButton("gone parent") {
                p.visibility = if (p.visibility == View.INVISIBLE) View.VISIBLE else View.INVISIBLE
            }
            addButton("release") {
                release()
            }

//            val s2 = TextureView(requireSceneContext())
//            s2.surfaceTextureListener = object :TextureView.SurfaceTextureListener{
//                override fun onSurfaceTextureAvailable(
//                    surface: SurfaceTexture,
//                    width: Int,
//                    height: Int
//                ) {
//                   // m.setSurface()
//                    m.setSurface(Surface(surface))
//                }
//
//                override fun onSurfaceTextureSizeChanged(
//                    surface: SurfaceTexture,
//                    width: Int,
//                    height: Int
//                ) {
//                }
//
//                override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
//                    return true
//                }
//
//                override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {
//                }
//            }

        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val v = view

        Log.d(TAG, "onViewCreated:1 ")
        launch {
            delay(100)

            startComplex()
            //surfaceView.visibility = View.GONE
//            delay(1000)
//            Log.d(TAG, "stop: $surfaceView ${surfaceF.value}")
//            release()
//            delay(1000)
//            m = MediaPlayer()
//            //surfaceView.visibility = View.VISIBLE
//            Log.d(TAG, "visibility: $surfaceView ${surfaceF.value}")
//            startComplex()
        }


    }


    val ob = object : DefaultLifecycleObserver {
        override fun onResume(owner: LifecycleOwner) {
            super.onResume(owner)
            owner.lifecycle.removeObserver(this)
            launch {
                startComplex()
            }
        }
    }

    override fun onPause() {
        super.onPause()
        release()
        lifecycle.addObserver(ob)
    }

    suspend fun startComplex() {
        m = MediaPlayer()
        Log.d(TAG, "startComplex:f1 ${surfaceF.value}")
        val f = surfaceF.mapNotNull { it.getOrNull() }.first()
        Log.d(TAG, "startComplex:f2 $f")
        m.setDisplay(f)
        delay(1200)
        m.setDataSource(s)
       withContext(Dispatchers.IO){
           m.prepare()
           m.start()
       }
    }


    fun release() {
        kotlin.runCatching {
            m.stop()
            m.reset()
            m.release()
        }
    }


    override fun onDestroyView() {
        super.onDestroyView()
        Log.d(TAG, "onDestroyView")

    }
}